<template>
	<div class="echart" :id="id" :style="{ width: width + 'px', height: '400px' }"></div>
</template>

<script>
	import * as echarts from 'echarts';

	export default {
		props: {
			id: String,
			width: Number
		},
		methods: {
			initChart(name, yData, xData) {
				let getchart = echarts.init(document.getElementById(this.id));
				var option = {
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'shadow'
						},
						backgroundColor: 'rgba(0,0,0,0.69)',
						borderColor: 'rgba(0,0,0,0.69)',
						textStyle: {
							color: '#fff'
						},
					},
					color: ['#FEE287', '#33BDFC', '#33FCC5', '#0079FE'],
					barWidth: 8,
					barGap: 0,
					legend: {
						bottom: '10%',
						left: 'center',
						textStyle: {
							color: '#fff'
						}
					},
					grid: {
						left: '4%',
						right: '4%',
						top: '4%',
						containLabel: true
					},
					xAxis: [{
						type: 'value',
						data: xData,
						name: '',
						min: 0,
						axisLine: {
							show: true,
							lineStyle: {
								color: 'rgba(51,189,252,0.5)'
							}
						},
						axisLabel: {
							formatter: '{value}',
							margin: 10,
							color:'#33BDFC'
							// interval:0,
							//  rotate:50//角度顺时针计算的
						},
						offset: 0,
						splitLine: {
							lineStyle: {
								color: 'rgba(51,189,252,0.5)'
							}
						}
					}],
					yAxis: [{
						type: 'category',
						data: xData,
						offset: 0,
						axisLine: {
							show: true,
							lineStyle: {
								color: 'rgba(51,189,252,0.5)'
							}
						},
						axisLabel: {
							width: '200',
							color:'#33BDFC',
							formatter: function(params) {
								let tip1 = '';
								let tip = '';
								let le = params.length; //图例文本的长度
								let num = 6
								if (le > num) {
									//几个字换行大于几就可以了
									let l = Math.ceil(le / num); //有些不能整除，会有余数，向上取整
									for (let i = 1; i <= l; i++) {
										//循环
										if (i < l) {
											//最后一段字符不能有\n
											tip1 += params.slice(i * num - num, i * num) + '\n'; //字符串拼接
										} else if (i === l) {
											//最后一段字符不一定够8个
											tip = tip1 + params.slice((l - 1) * num, le); //最后的拼接在最后
										}
									}
									return tip;
								} else {
									tip = params; //前面定义了tip为空，这里要重新赋值，不然会替换为空
									return tip;
								}
							},
						},
					}],
					series: yData
				};
				getchart.setOption(option);
				//随着屏幕大小调节图表
				window.addEventListener('resize', () => {
					getchart.resize();
				});
			}
		}
	};
</script>
